package com.tensquarespit2.service;

import com.tensquarespit2.dao.Spitdao;
import com.tensquarespit2.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

import java.util.Date;
import java.util.List;
import java.util.Queue;

@Service
@Transactional
public class Spitservice {
    @Autowired
    private Spitdao spitdao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    public List<Spit> findAll() {
        return spitdao.findAll();
    }

    public Spit findById(String id) {
        return spitdao.findById(id).get();
    }

    public void save(Spit spit) {
        spit.set_id(idWorker.nextId() + "");
        spit.setPublishtime(new Date());
        spit.setVisits(0);
        spit.setShare(0);
        spit.setThumbup(0);
        spit.setComment(0);
        spit.setState("1");
        String parentid = spit.getParentid();
        if (parentid != null && parentid != "") {
            Query query = new Query();
            Update update = new Update();
            query.addCriteria(Criteria.where("_id").is(parentid));
            update.inc("comment", 1);

            mongoTemplate.updateFirst(query, update, "spit");
        }

        spitdao.save(spit);
    }

    public void update(Spit spit) {
        spitdao.save(spit);
    }

    public void deleteById(String id) {
        spitdao.deleteById(id);
    }

    public Page<Spit> findByParentid(String parentid, int page, int size) {
        PageRequest pageable = PageRequest.of(page - 1, size);
        return spitdao.findByParentid(parentid, pageable);

    }

    public void dianzan(String id) {
        //Spit spit = spitdao.findById(id).get();
        /* spit.setThumbup((spit.getThumbup()==null ? 0:spit.getThumbup())+1);
        spitdao.save(spit);*/


        Query query = new Query();
        Update update = new Update();
        query.addCriteria(Criteria.where("_id").is(id));
        update.inc("thumbup", 1);

        mongoTemplate.updateFirst(query, update, "spit");
    }

}
